# -*- coding: utf-8 -*-
'''考虑把term封装成类，用面向对象的方式实现以下函数
'''
from datetime import timedelta, datetime

from dateutil import parser

from common.utils import tz

# FIXME: 北京PK10并不是每天都开奖，需要避开春节
# FIXME: 北京PK10有各种延迟开奖的问题，2017年3月28日出现严重滞后

START_DATE = parser.parse('2018-02-22 01:02:00')
START_DAY = parser.parse('2018-02-21 16:00:00')
START_TERM = 667279


def get_start_term(ts):
    day = datetime.fromtimestamp(ts)
    if day < START_DAY:
        raise RuntimeError('date too early')
    sub = day - START_DAY
    start_term = sub.days * 179 + START_TERM
    return start_term


def calc_term_by_ts(ts):
    """通过绝对时间来计算期数（无偏移量）
    """
    _, start_ts = tz.get_day_and_start_ts(ts)
    start_term = get_start_term(start_ts)
    sub = ts - start_ts
    # 09:02:00开始第一期，23:57:00结束，5分钟一期，共179期
    # 9 * 60 * 60 + 120 = 32520
    if sub < 32520:
        term = start_term
    # 23 * 60 * 60 + 57 * 60 = 86220
    elif sub < 86220:
        term = (sub - 32520) / 300 + start_term
    else:
        term = 179 + start_term
    return str(term)


def _plus_term(real_term, offset):
    return str(real_term + offset)


def _format_term(day, real_term):
    ts = tz.to_local_ts(day)
    return calc_term_by_ts(ts) + real_term - 1


def plus_term(term, offset):
    '''计算期号，offset可以为负数
    '''
    return _plus_term(int(term), offset)


def xrange_term(term, count, step=1):
    '''生成器，根据plus term生成一个迭代器，类似xrange
    '''
    if step == 0:
        raise ValueError('step must be not 0')
    if count == 0:
        yield term
    cur_count = 0
    while abs(cur_count) < abs(count):
        cur_count += 1
        if cur_count == 1:
            yield term
        else:
            term = plus_term(term, step)
            yield term


def calc_start_ts_by_term(term):
    """通过期数计算开始时间，用来手动开启当前期数（无偏移量）"""
    term = int(term)
    assert term >= START_TERM
    term -= START_TERM
    day = term / 179
    sub = term % 179
    date = START_DATE + timedelta(days=day)
    start_ts = tz.to_ts(date)
    return start_ts + sub * 300


def calc_stop_ts(start_ts):
    '''根据开始时间和当前的时间，来计算结束的时间，无偏移量
    '''
    term = calc_term_by_ts(start_ts)
    return calc_start_ts_by_term(term) + 300
